package com.example.demo.controller;

import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;

@RestController
public class redisController {

    @Autowired
    private BookService bookService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/redis")
    public String getredis(String id){
        //在redis查看是都已经存在验证码
        String code=redisTemplate.opsForValue().get(id);
        System.out.println("已经存在于redis"+!StringUtils.isEmpty(code));
        //存在则返回
        if(!StringUtils.isEmpty(code)){
            return code;
        }

        //从mysql中请求数据
        code=bookService.getCacheById(id).getName();
        System.out.println("从mysql中请求数据"+code);
        //判断code是否为空
        if(code!=null){
//            添加数据进入redis中，10分钟自动删除
            redisTemplate.opsForValue().set(id,code,10, TimeUnit.MINUTES);
            return code;
        }else {
            return "请求失败";
        }
    }
}
